package tulingxueyuan117;

import sun.reflect.generics.tree.Tree;

import java.util.*;

/**
 * Author: Zhang Dongwei
 * Date: 2022/11/4 10:37
 * 给你二叉树的根节点 root ，返回它节点值的 前序 遍历。
 */
public class p26_二叉树前序遍历_144 {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        TreeNode node1 = new TreeNode(2);
        TreeNode node2 = new TreeNode(3);
        root.right = node1;
        node1.left = node2;
        List<Integer> res = new ArrayList<>();
        res = preorderTraversal(root);
        System.out.println(res);
    }

//    和中序遍历类似
//    public static List<Integer> preorderTraversal(TreeNode root) {
//        List<Integer> res = new ArrayList<>();
//        accessNode(root, res);
//        return res;
//    }
//    public static void accessNode(TreeNode root, List<Integer> res){
//        if(root == null) return;
//        res.add(root.val);
//        accessNode(root.left, res);
//        accessNode(root.right, res);
//    }

//    循环迭代，需要借助栈
    public static List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Deque<TreeNode> stack = new LinkedList<TreeNode>();
        while (root != null || !stack.isEmpty()){
            while (root!=null){
                res.add(root.val);
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            root = root.right;
        }
        return res;
    }
}
